﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TvdbLib;
using TvdbLib.Cache;
using System.Windows;
using System.Collections.ObjectModel;

namespace TV_Organizer.TVDB
{
    [TVShowsConnector("TV DB")]
    public class TVDBConnector : ITVShowsConnector<TVDBShow>
    {
        #region fields

        TvdbHandler _tvdbHandler;

        #endregion
        #region Singleton pattern
        private TVDBConnector()
        {
            this.Initialize();
        }

        private static TVDBConnector m_instance = new TVDBConnector();
        public static TVDBConnector Instance
        {
            get { return m_instance; }
        }
        #endregion

        #region props

        private ObservableCollection<TVDBShow> _shows = new ObservableCollection<TVDBShow>();
        public IEnumerable<TVDBShow> Shows { get { return _shows; } }

        #endregion


        private void Initialize()
        {
            _tvdbHandler = new TvdbHandler(new XmlCacheProvider(Constants.CacheFile), Constants.APIKey);
            _tvdbHandler.InitCache();

            Application.Current.Dispatcher.BeginInvoke(new System.Action(() =>
            {
                Application.Current.Exit += (o, e) => _tvdbHandler.CloseCache();
            }));
        }

        public IEnumerable<TVDBShow> SearchShow(string search)
        {
            List<TVDBShow> results = new List<TVDBShow>();
            // Only 1 search at a time
            lock (_tvdbHandler)
            {
                //results = _tvdbHandler.SearchSeries(search, TvdbLib.Data.TvdbLanguage.DefaultLanguage);
            }
            return results;//.Select(r => new TVDBShow(r)).ToList();
        }



        public Episode GetEpisode(TVShow show, int season, int episode)
        {
            throw new NotImplementedException();
        }
    }
}
